package com.sevennotes.classtable

import android.Manifest
import android.content.Context
import android.content.SharedPreferences
import android.content.pm.PackageManager
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.util.Log
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.compose.setContent
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.layout.Column
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.SideEffect
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.compose.ui.unit.ExperimentalUnitApi
import androidx.core.content.edit
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.viewmodel.compose.viewModel
import com.sevennotes.classtable.config.*
import com.sevennotes.classtable.ui.pages.main_screen.MainScreen
import com.sevennotes.classtable.data.class_items.impl.ClassesRespositoryImpl
import com.sevennotes.classtable.ui.pages.main_screen.MainViewModel
import com.sevennotes.classtable.utils.CommonUtils
import kotlinx.coroutines.delay
import okhttp3.Dispatcher
import java.util.Date

private const val PREFS_NAME = "class_table_prefs"

class MainActivity : ComponentActivity() {

  private lateinit var myClassItemRespository: ClassesRespositoryImpl
  private lateinit var sharedPreferences: SharedPreferences

  private var mHandler = object : Handler(Looper.getMainLooper()) {
    override fun handleMessage(msg: Message) {

    }
  }

  @OptIn(ExperimentalUnitApi::class)
  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    myClassItemRespository = ClassesRespositoryImpl(applicationContext)
    sharedPreferences = getSharedPreferences(PREFS_NAME, MODE_PRIVATE)
    readSettings()
    setContent {
      if (Settings.windowWidth == 0 || Settings.windowHeight == 0) {
        Settings.windowWidth = LocalConfiguration.current.screenWidthDp
        Settings.windowHeight = LocalConfiguration.current.screenHeightDp
      }
      val mainScreenViewModel: MainViewModel = viewModel(
        factory = MainViewModel.provideFactory(myClassItemRespository)
      )
      RPermission()
      //保存数据
      CheckToSave(mainScreenViewModel)

      MainScreen(mainScreenViewModel)
    }
  }

  private fun isWifiConnected(): Boolean {
    val connectivityManager =
      getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
      val network = connectivityManager.activeNetwork ?: return false
      val networkCapabilities = connectivityManager.getNetworkCapabilities(network)
      return networkCapabilities?.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) == true
  }

  override fun onStop() {
    super.onStop()
    saveSettings()
  }

  @Composable
  private fun CheckToSave(mainScreenViewModel: MainViewModel) {
    LaunchedEffect(Unit) {
      if (!Settings.autoSaveEnable) {
        return@LaunchedEffect
      }
      if (Settings.shouldAutoSaveInMobileNetwork) {
        if (!isWifiConnected()) return@LaunchedEffect
      }
      val deltaTime = Date().time - Settings.lastAutoSaveDate
      val hours = deltaTime / (1000 * 60 * 60)
      if (hours >= 24 * Settings.autoSaveIntervalDays) {
        mainScreenViewModel.netBackupJsonFile(
          fileName = CommonUtils.generateFileNameWithDate(Settings.autoSaveFileName, "json"),
          autoSave = true
        ) {
          Toast.makeText(this@MainActivity, "自动上传数据：$it", Toast.LENGTH_SHORT).show()
          if (it == "上传成功!") {
            Settings.lastAutoSaveDate = Date().time
          }
        }
        delay(1000)
        mainScreenViewModel.checkAndDeleteExistSaveFiles()
      }
    }
  }

  @Composable
  private fun RPermission() {
    val context = LocalContext.current
    val lifecycle = LocalLifecycleOwner.current.lifecycle
    val permission = Manifest.permission.INTERNET
    val launcher = rememberLauncherForActivityResult(
      contract = ActivityResultContracts.RequestPermission(),
      onResult = {
          Toast.makeText(context, if (it)"申请成功" else "申请失败", Toast.LENGTH_SHORT).show()
      }
    )
    val lifecycleObserver = remember {
      LifecycleEventObserver { _, event ->
        if (event == Lifecycle.Event.ON_START) {
          if (!permission.isGrantedPermission(context)) {
            launcher.launch(permission)
          }else {
            Log.d("test","我有权限呵呵")
          }
        }
      }
    }

    DisposableEffect(lifecycle, lifecycleObserver) {
      lifecycle.addObserver(lifecycleObserver)
      onDispose { lifecycle.removeObserver(lifecycleObserver) }
    }
  }

  private fun String.isGrantedPermission(context: Context):Boolean {
    return context.checkSelfPermission(this) == PackageManager.PERMISSION_GRANTED
  }

  private fun readSettings() {
    Settings.currentTableNameId = sharedPreferences.getInt(CURRENT_TABLE_NAME, -1)
    Settings.windowWidth = sharedPreferences.getInt(WINDOW_WIDTH, 0)
    Settings.windowHeight = sharedPreferences.getInt(WINDOW_HEIGHT, 0)
    Settings.widthPercent = sharedPreferences.getFloat(WIDTH_PERCENT, 0f)
    Settings.heightPercent = sharedPreferences.getFloat(HEIGHT_PERCENT, 0f)
    Settings.beginHour = sharedPreferences.getInt(BEGIN_HOUR,8)
    Settings.endHour = sharedPreferences.getInt(END_HOUR,20)
    Settings.webDavUrl = sharedPreferences.getString(WEB_DAV_URL,"https://dav.jianguoyun.com/dav/")!!
    Settings.webDavUsername = sharedPreferences.getString(WEB_DAV_USERNAME,"")!!
    Settings.webDavPassword = sharedPreferences.getString(WEB_DAV_PASSWORD,"")!!
    Settings.dirName = sharedPreferences.getString(DIRNAME,"classTable")!!
    Settings.lastAutoSaveDate = sharedPreferences.getLong(LAST_AUTO_SAVE_DATE, 0L)
    Settings.maxAutoSaveFileNumber = sharedPreferences.getInt(MAX_AUTOSAVE_FILE_NUMBER, 7)
    Settings.autoSaveIntervalDays = sharedPreferences.getInt(AUTOSAVE_INTERVAL_DAYS, 1)
    Settings.shouldAutoSaveInMobileNetwork = sharedPreferences.getBoolean(SHOULD_AUTOSAVE_IN_MOBILE, false)
    Settings.autoSaveEnable = sharedPreferences.getBoolean(AUTOSAVE_ENABLE, false)
    val r = sharedPreferences.getFloat(THEME_COLOR_R, 0.4117f)
    val g = sharedPreferences.getFloat(THEME_COLOR_G, 0.6078f)
    val b = sharedPreferences.getFloat(THEME_COLOR_B, 0.4392f)
    Settings.themeColor = Color(r, g, b)
  }

  private fun saveSettings() {
    sharedPreferences.edit {
      putInt(CURRENT_TABLE_NAME, Settings.currentTableNameId)
      putInt(WINDOW_WIDTH, Settings.windowWidth)
      putInt(WINDOW_HEIGHT, Settings.windowHeight)
      putFloat(WIDTH_PERCENT, Settings.widthPercent)
      putFloat(HEIGHT_PERCENT, Settings.heightPercent)
      putInt(BEGIN_HOUR, Settings.beginHour)
      putInt(END_HOUR, Settings.endHour)
      putString(WEB_DAV_URL, Settings.webDavUrl)
      putString(WEB_DAV_USERNAME, Settings.webDavUsername)
      putString(WEB_DAV_PASSWORD, Settings.webDavPassword)
      putString(DIRNAME, Settings.dirName)
      val color = Settings.themeColor
      putFloat(THEME_COLOR_R, color.red)
      putFloat(THEME_COLOR_G, color.green)
      putFloat(THEME_COLOR_B, color.blue)
      putLong(LAST_AUTO_SAVE_DATE, Settings.lastAutoSaveDate)
      putInt(MAX_AUTOSAVE_FILE_NUMBER, Settings.maxAutoSaveFileNumber)
      putInt(AUTOSAVE_INTERVAL_DAYS, Settings.autoSaveIntervalDays)
      putBoolean(SHOULD_AUTOSAVE_IN_MOBILE, Settings.shouldAutoSaveInMobileNetwork)
      putBoolean(AUTOSAVE_ENABLE, Settings.autoSaveEnable)
      commit()
    }
  }
}
